import multer from "multer";
import fs from "fs";
import crypto from "crypto";
import path from "path";

import { INext, IRes } from "@src/routes/common/types";
import { resExample } from "@src/services/common/responseData";
import { Request } from "express";

const uploadDir = '/public/images/';

const storage = multer.memoryStorage(); // 使用内存存储

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 1024 * 1024 * 5 // 限制文件大小为5MB
    },
});

const checkFileExists = (filePath: string) => {
    return new Promise((resolve) => {
        fs.access(filePath, fs.constants.F_OK, (err) => {
            resolve(!err); // 返回文件是否存在
        });
    });
}

const singleFileUpload = (filename: string) => {
    return async (req: Request, res: IRes, next: INext) => {
        upload.single(filename)(req, res, async (err) => {
            if (err) {
                console.error('上传失败:', err);
                return next(resExample({
                    code: 400,
                    success: false,
                    data: null,
                    message: err.code
                }));
            }

            const file = req.file!;
            if(!file){
                return next(resExample({
                    code: 400,
                    success: false,
                    data: null,
                    message: '文件不存在'
                }))
            }
            const hash = crypto.createHash('sha256');
            hash.update(file.buffer);
            const fileHash = hash.digest('hex');
            const extname = path.extname(file.originalname);
            const filePath = `${process.cwd()}${uploadDir}${fileHash}${extname}`
            
            const exists = await checkFileExists(filePath);
            if (exists) {
                // 文件已存在，直接返回
                req.file!.filename = `${fileHash}${extname}`
            } else {
                // 新文件，保存
                fs.writeFileSync(filePath, file.buffer);
                req.file!.filename = `${fileHash}${extname}`
            }
            next()
        });
    };
}

export default singleFileUpload
